package com.ruoyi.business.component.mqconsumer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.LoanDeferredOrder;
import com.ruoyi.bizsys.mapper.RepaymentOrderMapper;
import com.ruoyi.bizsys.service.ILoanDeferredOrderService;
import com.ruoyi.business.service.IBRepaymentService;
import com.ruoyi.business.service.IRepaymentService;
import com.ruoyi.business.service.asyncservice.AsyncRepaymentService;
import com.ruoyi.common.config.RocketMqTopics;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.FeishuUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 钱包消费
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumers.walletConsumer}",
        topic = "${rocketmq.consumer-topics.walletChangeTopic}",
        selectorType = SelectorType.TAG,
        selectorExpression = "1",
        messageModel = MessageModel.CLUSTERING,
        consumeTimeout = 300L)
public class WalletChangeMqConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
    @Autowired
    IRepaymentService iRepaymentService;

    @Autowired
    RepaymentOrderMapper repaymentOrderMapper;

    @Autowired
    IBRepaymentService iBRepaymentService;

    @Autowired
    ILoanDeferredOrderService loanDeferredOrderService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    AsyncRepaymentService asyncRepaymentService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String messageId = messageExt.getMsgId();
        log.info("钱包变动 MQ 开始消费，第 {} 次 >>> messageId = {}", messageExt.getReconsumeTimes(), messageId);
        JSONObject data = JSONObject.parseObject(new String(messageExt.getBody()));
        log.info("钱包变动 MQ，messageId = {}, messageBody = {}", messageId, data);
        String custNo = data.get("custNo").toString();
        try {
            log.info("钱包变动 MQ 消费开始 >>> custNo = {}, messageId = {}, messageBody = {}", custNo, messageId);
            doHhandle(custNo);
        } catch (Exception e) {
            // 发送监控
            log.error("钱包变动 MQ 的消费 error：custNo = {}，messageId = {}", custNo, messageId, e);
            FeishuUtils.sendFeishuToMonit("WalletChangeMqConsumer" + "." + custNo, "MQ 消费者-钱包变动", custNo, data.toJSONString(), e);
            throw new RuntimeException(e);
        }
        log.info("钱包变动 MQ 消费结束 >>> custNo = {}，messageId = {}", custNo, messageId);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        // 设置最大重试次数
        consumer.setMaxReconsumeTimes(RocketMqTopics.getMaxReconsumeTimes());
        // 如下，设置其它consumer相关属性
        // consumer.setPullBatchSize(16);
    }

    public void doHhandle(String custNo) {
        String redisKey = "walletDefer_" + custNo;
        String walletDefer = redisCache.getCacheObject(redisKey);
        log.info("钱包变动mq消费,查询redis：walletDefer:{}", walletDefer);
        if (StringUtils.isEmpty(walletDefer)) {
            log.info("钱包变动mq消费,redis无数据：custNo:{}", custNo);
            return;
        }
        // 查询延期是否存在为9的，
        LoanDeferredOrder loanDeferredOrder = loanDeferredOrderService.getOne(new QueryWrapper<LoanDeferredOrder>()
                .eq("cust_no", custNo)
                .eq("status", LoanDeferredOrder.STATUS_WAIT)
                .last("limit 1")
        );
        if (null == loanDeferredOrder) {
            log.info("钱包变动mq消费,loanDeferredOrder无延期数据：custNo:{}", custNo);
            redisCache.deleteObject(redisKey);
            return;
        }
        // 查询钱包，然后在冻结钱包，生成order ，为5 发送mq
        asyncRepaymentService.asyncWalletBuyDefer(loanDeferredOrder, false);
    }

}
